package com.ztom.top100;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 二叉树的最大深度
 * <p>
 * https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
 *
 * @author ZhangTao
 */
public class Code42MaxDepth {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归
     *
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }


    /**
     * 迭代: 层次遍历, 记录最大层数
     *
     * @param root
     * @return
     */
    public int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Deque<TreeNode> queue = new LinkedList<>();
        queue.addFirst(root);
        int max = 0;
        TreeNode node = null;
        while (!queue.isEmpty()) {
            int curLevelSize = queue.size();
            while (curLevelSize-- > 0) {
                node = queue.pollLast();
                if (node != null) {
                    if (node.left != null) {
                        queue.addFirst(node.left);
                    }
                    if (node.right != null) {
                        queue.addFirst(node.right);
                    }
                }
            }
            max++;
        }
        return max;
    }
}
